<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Nginx-1 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="在nginx之前 同步异步阻塞非阻塞、并发并行 1）同步与异步 同步：当一个同步调用发出后，调用者要一直等待调用的结果返回，才能进行后续的执行 异步" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Nginx-1 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Nginx-1" />
<meta property="og:description" content="在nginx之前 同步异步阻塞非阻塞、并发并行 1）同步与异步 同步：当一个同步调用发出后，调用者要一直等待调用的结果返回，才能进行后续的执行 异步" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/" />
<meta property="article:published_time" content="2017-08-01T10:02:06+08:00" />
<meta property="article:modified_time" content="2017-08-01T10:02:06+08:00" />
<meta itemprop="name" content="Nginx-1">
<meta itemprop="description" content="在nginx之前 同步异步阻塞非阻塞、并发并行 1）同步与异步 同步：当一个同步调用发出后，调用者要一直等待调用的结果返回，才能进行后续的执行 异步">
<meta itemprop="datePublished" content="2017-08-01T10:02:06&#43;08:00" />
<meta itemprop="dateModified" content="2017-08-01T10:02:06&#43;08:00" />
<meta itemprop="wordCount" content="4716">



<meta itemprop="keywords" content="," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Nginx-1"/>
<meta name="twitter:description" content="在nginx之前 同步异步阻塞非阻塞、并发并行 1）同步与异步 同步：当一个同步调用发出后，调用者要一直等待调用的结果返回，才能进行后续的执行 异步"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/"
    >Nginx-1</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/" class="article-date">
  <time datetime="2017-08-01 10:02:06 &#43;0800 CST" itemprop="datePublished">2017-08-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/linux/"> Linux </a>
</span>  
  <span class="article-tag">
    <i class="icon icon-tags"></i>&nbsp;
    <a class="article-tag-link" href="/tags//">  </a>
  </span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 4716words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 10minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="在nginx之前">在nginx之前</h1>
<h2 id="同步异步阻塞非阻塞并发并行">同步异步阻塞非阻塞、并发并行</h2>
<p>1）同步与异步</p>
<ul>
<li>同步：当一个同步调用发出后，调用者要一直等待调用的结果返回，才能进行后续的执行</li>
<li>异步：当一个异步调用发出后，调用者不必一直等待调用结果的返回；异步调用要获取结果，有两种方式：
<ul>
<li>主动轮询异步调用的结果</li>
<li>被调用方通过callback（回调通知）来通知调用方调用结果</li>
</ul>
</li>
</ul>
<p>2）阻塞与非阻塞</p>
<p>阻塞与非阻塞的重点在于进/线程等待消息时的行为：在等待消息的时候，当前线程是挂起状态，还是非挂起状态</p>
<ul>
<li>阻塞：调用发出后，在消息返回前，当前线程被挂起，直到有消息返回，当前进/线程才会被激活</li>
<li>非阻塞：调用发出后，不会阻塞当前进/线程，而会立即返回</li>
</ul>
<p>总结：同步与异步，重点在于消息通知的方式；阻塞与非阻塞，重点在等待消息时的行为。</p>
<p>Nginx采用异步非阻塞的方式工作。跟Linux中的epoll模型有关。</p>
<p>3）并发与并行</p>
<p>并发（concurrency）和并行（parallellism）是：</p>
<ul>
<li>解释一：并行是指两个或者多个事件在同一时刻发生；而并发是指两个或多个事件在同一时间间隔发生。</li>
<li>解释二：并行是在不同实体上的多个事件，并发是在同一实体上的多个事件。</li>
<li>解释三：在一台处理器上“同时”处理多个任务，在多台处理器上同时处理多个任务。</li>
</ul>
<p>如hadoop分布式集群 所以并发编程的目标是充分的利用处理器的每一个核，以达到最高的处理性能</p>
<h2 id="epoll">epoll</h2>
<p>I/O多路复用的epoll模型</p>
<p>当有I/O事件产生时，epoll就会去告诉进程哪个链接有I/O事件，然后进程就去处理这个事件</p>
<h2 id="nginx原理">nginx原理</h2>
<p>每进来一个request，会有一个worker进程去处理。但不是全程处理，处理到可能发生阻塞的地方。比如向后端服务器转发request，并等待结果返回。那么，这个worker不会这么傻等着，他会在发完请求后，注册一个事件：“如果后端服务返回了，告诉我一声，我接着干”。于是他休息去了。此时，如果再有新的request进来，他就可以很快再以这种方式处理。而一旦后端服务返回了，就会触发这个事件，worker才会来接手，这个request都会接着往下走。通过这种快速处理，快速释放请求的方式，达到同样的配置可以处理更大并发量的目的。</p>
<h1 id="概述">概述</h1>
<p>nginx是一个高性能的HTTP和反向代理web服务器，同时也提供了IMAP/POP3/SMTP服务。</p>
<p>nginx支持fastCGI（默认支持）</p>
<p>nginx有两种工作模式</p>
<ul>
<li>master-worker模式</li>
<li>单进程模式</li>
</ul>
<p>master-worker模式：有一个master进程和至少一个worker进程。master进程负责处理系统信号、加载配置、管理worker进程（启动、杀死、监控、发送消息/信号等）。worker进程负责处理具体业务逻辑，也就是说，真正提供服务的是worker进程。生产环境下一般使用这种模式。</p>
<p>单进程模式：todo&hellip;</p>
<h2 id="模块分类">模块分类</h2>
<ul>
<li>核心模块：HTTP模块、EVENT模块和MAIL模块</li>
<li>基础模块：HTTP Access、HTTP FastCGI、HTTP Proxy、HTTP Rewrite</li>
<li>第三方模块：HTTP Upstream Request Hash、Notive、HTTP Access Key</li>
</ul>
<p>nginx的高并发利益于采用epoll模型，epoll模型是linux2.6以后才出现，apache采用select模型。</p>
<h2 id="应用场景">应用场景</h2>
<p>三大应用场景</p>
<ul>
<li>静态资源服务</li>
<li>反向代理服务</li>
<li>API服务</li>
</ul>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708164810.png" alt=""></p>
<p>静态页面、JavaScript等可以由nginx直接访问</p>
<h2 id="nginx的组成">nginx的组成</h2>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708164825.png" alt=""></p>
<h1 id="安装linux">安装（linux）</h1>
<p>官网：http://nginx.org/</p>
<p>安装环境：CentOS 7</p>
<h2 id="方式一make">方式一：make</h2>
<ul>
<li>
<p>安装nginx依赖的其它包</p>
<ul>
<li>pcre-devel,nginx的配置文件中使用了正则表达式，因此要安装来支持。</li>
<li>还有其它的依赖，如gcc、gcc-c++、zlib-devel、openssl-devel等，根据需要来安装(一般都建议安装上)。</li>
</ul>
</li>
<li>
<p>安装 nginx</p>
</li>
</ul>
<pre><code>$ wget http://nginx.org/download/nginx-1.12.1.tar.gz
$ tar -zxvf nginx-1.12.1.tar.gz
$ cd nginx-1.12.1/
$ ./configure
$ make
$ sudo make install

</code></pre>
<p>默认安装在<code>/usr/local/nginx</code>，也可以在<code>./configure</code>时指定安装的路径<code>./configure --prefix=/home/geek/nginx</code></p>
<p>默认安装的<code>log</code>和<code>conf</code>都在<code>/usr/local/nginx</code>下面，log文件不应该放在这里？？todo&hellip;.</p>
<p><code>/usr/local/nginx</code>目录如下：</p>
<pre><code>├── conf
│   ├── fastcgi.conf
│   ├── fastcgi.conf.default
│   ├── fastcgi_params
│   ├── fastcgi_params.default
│   ├── koi-utf
│   ├── koi-win
│   ├── mime.types
│   ├── mime.types.default
│   ├── nginx.conf
│   ├── nginx.conf.default
│   ├── scgi_params
│   ├── scgi_params.default
│   ├── uwsgi_params
│   ├── uwsgi_params.default
│   └── win-utf
├── html
│   ├── 50x.html
│   └── index.html
├── logs
│   ├── access.log
│   ├── error.log
│   └── nginx.pid
├── sbin
│   └── nginx
</code></pre>
<p>源码安装官方文档：http://nginx.org/en/docs/configure.html</p>
<ul>
<li>启动 &amp; 关闭</li>
</ul>
<pre><code class="language-shell">$ sudo /usr/local/nginx/sbin/nginx -t       # 检查配置信息是否有错

$ sudo /usr/local/nginx/sbin/nginx          # 启动nginx，虚拟机要关闭防火墙或开放80端口

$ sudo /usr/local/nginx/sbin/nginx -s stop  # 强制停止nginx

$ sudo /usr/local/nginx/sbin/nginx -s quit  # 优雅关闭nginx

$ sudo /usr/local/nginx/sbin/nginx -s reload # 重新加载nginx.conf文件

$ /usr/local/nginx/sbin/nginx -v            # 显示nginx版本信息

</code></pre>
<h2 id="方式二yum">方式二：yum</h2>
<p>1）先安装yum-utils</p>
<pre><code class="language-shell">sudo yum install yum-utils
</code></pre>
<p>2）添加yum源</p>
<pre><code class="language-shell">vim /etc/yum.repos.d/nginx.repo
</code></pre>
<p>添加以下内容</p>
<pre><code class="language-tex">[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
</code></pre>
<p>3）安装nginx</p>
<pre><code class="language-shell">sudo yum install nginx
</code></pre>
<p>默认安装最新的stable版本，以后也可以通过上面配置的yum源来更新版本</p>
<p>官方文档：http://nginx.org/en/linux_packages.html#RHEL-CentOS</p>
<pre><code class="language-shell">[root@localhost test]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz
</code></pre>
<h2 id="方式三docker">方式三：docker</h2>
<h1 id="nginx常用命令">nginx常用命令</h1>
<p>命令格式：nginx -s reload</p>
<ul>
<li>帮助：-? -h</li>
<li>使用指定的配置文件：-c</li>
<li>指定配置指令：-g</li>
<li>指定运行目录：-p</li>
<li>发送信号：-s
<ul>
<li>立即停止服务：nginx -s stop</li>
<li>优雅停止服务：nginx -s quit</li>
<li>重载配置文件：nginx -s reload</li>
<li>重新开始记录日志文件：nginx -s reopen</li>
</ul>
</li>
<li>测试配置文件是否有语法错误：-t -T</li>
<li>打印nginx版本、编译信息：-v -V</li>
</ul>
<h1 id="nginxconf">nginx.conf</h1>
<h2 id="本机nginxconf文件位置的说明">本机nginx.conf文件位置的说明</h2>
<p>centos 7 使用 yum 安装的 nginx 默认的安装目录如下：</p>
<pre><code class="language-shell">[root@localhost docs]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz
</code></pre>
<p>所有配置文件位于 /etc/nginx/ 下，/etc/nginx/nginx.conf是主配置文件，它使用了include指令引入的其它位置的配置文件。</p>
<p>也就是配置文件有 /etc/nginx/nginx.conf 和 /etc/nginx/conf.d/*.conf</p>
<p>nginx.conf：</p>
<pre><code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] &quot;$request&quot; '
                      '$status $body_bytes_sent &quot;$http_referer&quot; '
                      '&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
</code></pre>
<h2 id="配置文件结构">配置文件结构</h2>
<p>配置文件结构，三大部分：</p>
<ol>
<li>主配置块：从开始到even块之间的内容</li>
<li>even块：主要影响Nginx服务器与用户的网络连接</li>
<li>http块：
<ol>
<li>http全局块</li>
<li>upstream块</li>
<li>server块
<ol>
<li>全局server块</li>
<li>location块</li>
</ol>
</li>
</ol>
</li>
</ol>
<pre><code>main block  # 主配置段，即全局配置，对http/mail都有效

events {
    worker_connections  1024;
}

http {
    upstream ifacesuportservice_dyexp {

    }
    gzip  on;
    server {
        listen       80;
        server_name  localhost;
        location /webstatic {
               gzip off;
        }
    }
    server {
        listen       81;
        server_name  www.baidu.com;
        location /webstatic {
        
        }
    }
}
mail {
    
}
stream {
    
}
</code></pre>
<p>指令块由一个块配置项名和一对大括号组成。常用的有http、server、upstream、location。</p>
<h2 id="配置语法">配置语法</h2>
<ul>
<li>配置文件由指令和指令块构成</li>
<li>每条指令以<code>;</code>结尾，指令与参数之间以空格分隔</li>
<li>指令块以{}大括号将多条指令组织在一起</li>
<li>include语句允许组合多个配置文件，以提高可以维护性</li>
<li>使用#符号添加注释，提高可读性</li>
<li>使用$符号使用变量</li>
<li>部分指令的参数支持正则表达式</li>
</ul>
<h2 id="参数单位">参数单位</h2>
<ul>
<li>
<p>时间</p>
<ul>
<li>ms,milliseconds</li>
<li>s,seconds</li>
<li>m,minutes</li>
<li>h,hours</li>
<li>d,days</li>
<li>w,weeks</li>
<li>M,months,30d ays</li>
<li>y,years,365 days</li>
</ul>
</li>
<li>
<p>空间</p>
<ul>
<li>不写单位，bytes</li>
<li>k/K,kilobytes</li>
<li>m/M,megabytes</li>
<li>g/G,gigabytes</li>
</ul>
</li>
</ul>
<h2 id="配置变量">配置变量</h2>
<ul>
<li>内建变量，由nginx模块提供，可直接引用，官网：http://nginx.org/en/docs/varindex.html</li>
<li>自定义变量，用户使用set命令定义，<code>set variable_name value</code></li>
<li>引用变量，<code>$variable_name</code></li>
</ul>
<h2 id="全局配置">全局配置</h2>
<p>1）性能优化相关配置</p>
<ul>
<li>worker_processes number | auto,worker进程数量，通常为主机的物理核数</li>
<li>worker_cpu_affinity</li>
<li>worker_priority</li>
<li>worker_rlimit_nofile</li>
</ul>
<p>2）events事件驱动相关配置</p>
<pre><code>events {
    worker_connections  1024;
    accept_mutex on | off;
}
</code></pre>
<p>accept_mutex on | off 互斥，处理新的连接请求</p>
<ul>
<li>on指由各个worker轮流处理新请求</li>
<li>off指每个新请求的到达都会通知（唤醒）所有进程，但只有一个进程可获得连接，造成“惊群”，影响性能</li>
</ul>
<p>3）调试和定位问题</p>
<ul>
<li><code>daemon on | off;</code>是否以守护进程运行nginx，默认on</li>
<li><code>master_process on | off;</code>是否以master/worker模型运行nginx，默认on</li>
<li><code>error_log file [level];</code>错误日志文件及其级别，出于调试需要，可设定为debug，但debug仅在编译时使用了 &ndash;with-debug 选项时才有效，默认：<code>error_log logs/error.log error;</code></li>
</ul>
<h2 id="静态资源web服务器">静态资源web服务器</h2>
<p>首先，本机nginx环境：</p>
<pre><code class="language-shell">[root@localhost docs]# whereis nginx
nginx: /usr/sbin/nginx /usr/lib64/nginx /etc/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz
</code></pre>
<p>1）将tomcat 9 的 docs 上传到 /usr/share/nginx/tomcat9/</p>
<p>2）配置nginx.conf</p>
<p>最简单的配置</p>
<pre><code>server {
    listen       8080;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
        alias /usr/share/nginx/tomcat9/docs/;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
</code></pre>
<p>做了两点修改：</p>
<ol>
<li>监听8080端口</li>
<li>在 location / 块 使用了 alias，而没有使用 root</li>
</ol>
<hr>
<p>在http块中，开启 gzip，这里的数字仅用于测试，压缩后文件小了很多：</p>
<pre><code>gzip on;
gzip_min_length 1;
gzip_comp_level 2;
gzip_types text/plain application/xml;
</code></pre>
<p>参考官方：http://nginx.org/en/docs/http/ngx_http_gzip_module.html</p>
<p>参考博客：https://blog.csdn.net/bigtree_3721/article/details/79849503</p>
<hr>
<p>关于日志</p>
<p>日志配置所在的块结构内的日志都会记录在相应的目录</p>
<p>如上面 server 块内的 <code>access_log  /var/log/nginx/host.access.log  main</code>会记录所有请求8080端口的日志</p>
<h2 id="配置多台虚拟主机">配置多台虚拟主机</h2>
<p>在nginx.conf的http块下配置多个server块就是多个虚拟主机</p>
<p>server块要配置不同的server_name以表示主机名，然后需要在hosts文件中做ip与主机之间的映射</p>
<pre><code>http {
    upstream ifacesuportservice_dyexp {

    }

    server {
        listen       80;
        server_name  localhost;
        location /webstatic {
               gzip off;
        }
    }
    server {
        listen       81;
        server_name  www.baidu.com;
        location /webstatic {
        
        }
    }
}
</code></pre>
<h2 id="日志">日志</h2>
<p>1）在http块中定义日志格式</p>
<pre><code>    log_format  main  '$remote_addr - $remote_user [$time_local] &quot;$request&quot; '
                      '$status $body_bytes_sent &quot;$http_referer&quot; '
                      '&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;';
</code></pre>
<p>2）在各个块（http、server）中引用日志格式，并指定日志位置、日志文件名称</p>
<pre><code>   access_log  /var/log/nginx/access.log  main;
</code></pre>
<p>日志配置所在的块结构内的日志都会记录在相应的目录，也就是各个块的日志可以分开记录</p>
<hr>
<p>日志切分——实现一个定时任务处理nginx日志</p>
<p>1）编写一个shell脚本<code>log.sh</code>，定义如何切分（备份）日志</p>
<pre><code class="language-sh">#!/bin/sh

BASE_DIR=/usr/local/nginx
BASE_FILE_NAME=bhz.com.access.log

CURRENT_PATH=$BASE_DIR/logs
BAK_PATH=$BASE_DIR/datalogs

CURRENT_FILE=$CURRENT_PATH/$BASE_FILE_NAME
BAK_TIME=`/bin/date -d yesterday +%Y%m%d%H%M`
BAK_FILE=$BAK_PATH/$BAK_TIME-$BASE_FILE_NAME
echo $BAK_FILE

$BASE_DIR/sbin/nginx -s stop

mv $CURRENT_FILE $BAK_FILE

$BASE_DIR/sbin/nginx
</code></pre>
<p>2）实现定时任务</p>
<pre><code>crontab -e
</code></pre>
<p>添加内容如下：</p>
<pre><code>*/1 * * * * * sh /usr/local/nginx/sbin/log.sh
</code></pre>
<p>记得修改为自己的文件路径</p>
<h2 id="location块">location块</h2>
<p>语法：</p>
<pre><code>Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:	—
Context:	server, location
</code></pre>
<p>官方文档：http://nginx.org/en/docs/http/ngx_http_core_module.html#location</p>
<ul>
<li>location = pattern {} 精准匹配</li>
<li>location ~ pattern {} 正则匹配，大小写敏感</li>
<li>location ~* pattern {} 正则匹配，大小写不敏感</li>
<li>location ^~ /path/path {} 不检查正则表达式</li>
</ul>
<pre><code>    location = /50x.html {
        root   /usr/share/nginx/html;
    }
</code></pre>
<p>题外话：可以安装一个【正则表达式终端测试工具】来测试正则表达式：</p>
<pre><code class="language-shell"># yum install -y pcre-tools
</code></pre>
<p>如何使用？</p>
<ul>
<li>re：输入正则表达式，//表示开头和结束</li>
<li>data：测试的数据</li>
</ul>
<pre><code>[root@localhost ~]# pcretest 
PCRE version 8.32 2012-11-30

  re&gt; /(\d+)\.(\d+)\.(\d+)\.(\d+)/
data&gt; 192.168.12.133
 0: 192.168.12.133
 1: 192
 2: 168
 3: 12
 4: 133
</code></pre>
<h2 id="rewrite的写法">rewrite的写法</h2>
<p>官方文档：http://nginx.org/en/docs/http/ngx_http_rewrite_module.html</p>
<pre><code>Syntax:	rewrite regex replacement [flag];
Default:	—
Context:	server, location, if
</code></pre>
<p>flag有</p>
<ul>
<li>last	本条规则匹配完成后继续向下匹配新的location URI规则</li>
<li>break	本条规则匹配完成后终止，不在匹配任何规则</li>
<li>redirect	返回302临时重定向，地址栏改变</li>
<li>permanent	返回301永久重定向，地址栏改变</li>
</ul>
<p>参考：https://www.cnblogs.com/brianzhu/p/8624703.html</p>
<p>last与break区别：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img-07/20200708164930.png" alt=""></p>
<p>参考：https://www.bilibili.com/video/av55805198?p=67</p>
<p>总结：</p>
<ul>
<li>last，匹配到路径后，会按照新的路径请求一次nginx</li>
<li>break，匹配到路径后，不会按照新的路径请求一次nginx，而是会去root目录寻找文件；如果在location中，则用break，则不是last。</li>
</ul>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/" title="Nginx-1" target="_blank" rel="external">https://rulerLwx.gitee.io/2017/08/nginx-1-%E5%9F%BA%E7%A1%80/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2017/08/docker-1-%E5%9F%BA%E7%A1%80/" title="Docker-1-基础"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2017/08/nginx-2-%E5%9F%BA%E7%A1%80/"
                    title="Nginx-2"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
